package org.xi.behavioral.observer.impl;

import org.xi.behavioral.observer.api.Observer;
import org.xi.behavioral.observer.api.Subject;

import java.util.LinkedHashSet;
import java.util.Set;

public class MessagePublisher implements Subject {
    private final Set<Observer> subscribers = new LinkedHashSet<>();
    private String latestNews;

    @Override
    public void registerObserver(Observer observer) {
        subscribers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        subscribers.remove(observer);
    }

    @Override
    public void notifyObservers() {
        for (Observer subscriber : subscribers) {
            subscriber.notify(latestNews);
        }
    }

    public void publishNewArticle(String news) {
        latestNews = news;
        System.out.println("New article published: " + news);
        notifyObservers();
    }
}